package misc;

import java.io.IOException;

import com.sun.net.httpserver.HttpExchange;

/**
 * @author Filip Lindqvist <buggfille@gmail.com>
 * @created 7:38:27 PM - Nov 24, 2011
 */
public class HttpStream {
    protected HttpExchange exchange;
    protected long bytesSent = 0;
    private final StringBuffer response;
    private final int code;
    private final String ENCODING = "utf8";

    protected HttpStream(HttpExchange t, int code) {
        exchange = t;
        response = new StringBuffer();
        this.code = code;
    }

    protected HttpStream(HttpExchange t) {
        this(t, HTTP.OK);
    }

    public void close() throws IOException {
        exchange.sendResponseHeaders(code, response.length());
        exchange.getResponseBody()
                .write(response.toString().getBytes(ENCODING));
        exchange.getResponseBody().close();
        bytesSent = response.length();
        // System.out.println(bytesSent + "sent.. closing..");
    }

    public HttpStream write(String s) throws IOException {
        response.append(s);
        return this;
    }

    public long getBytesSent() {
        return bytesSent;
    }

}
